package com.db.derby;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Student on 27.11.2014.
 */
public class DBConnection {
    private static final String dbURL = "jdbc:derby:chatdb;create=true";

    private static Connection conn;

    public static Connection getConn() {
        try {
            if (conn == null || conn.isClosed())
                createConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    private static void createConnection() {
        try {
            conn = DriverManager.getConnection(dbURL);
            createMainTables();
        } catch (Exception except) {
            except.printStackTrace();
        }
    }

    public static void stopConnection() {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private static void createMainTables() {
        try (Statement stmt = conn.createStatement()) {

            try {
                stmt.executeUpdate("create table app.history(id INT not null primary key\n" +
                        "GENERATED ALWAYS AS IDENTITY, user_name varchar(300) not null,\n" +
                        "  date_time TIMESTAMP DEFAULT current_timestamp,\n" +
                        "  message varchar(300), room varchar(300))");
                System.out.println("app.history created");
            } catch (Exception e) {

            }

            try {
                stmt.executeUpdate("create table app.private_history(id INT not null primary key\n" +
                        "GENERATED ALWAYS AS IDENTITY, user_name varchar(300) not null ,\n" +
                        "  date_time TIMESTAMP DEFAULT current_timestamp,\n" +
                        "  message varchar(300),\n" +
                        "addressee varchar(300), room varchar(300))");
                System.out.println("app.private_history created");
            } catch (Exception e) {
            }

            try {
                stmt.executeUpdate("create table app.users(user_name varchar(300) not null PRIMARY KEY ,\n" +
                        "password varchar(300))");
                System.out.println("app.users created");
            } catch (Exception e) {
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
